<script>
//import { ref, onMounted, watch } from 'vue';
import AMapLoader from "@amap/amap-jsapi-loader";
import Swal from 'sweetalert2';
import axios from 'axios';
import MarkerIcon from '@/assets/MarkerIcon.png';
//import { getLocations, deleteLocation } from '@/api/locations'; // 假设这是您的新API文件

export default {
  data() {
    return {
      map: null,
      markers: [],
      delmarkers: [],
      newmarkers: [],
      filteredMarkers: [],
      allmarkers: [],
      searchKeyword: '',
      newmarker: null,
      buttonText: '添加标点',
      ifaddmarker: false,
      icon: null
    };
  },
  mounted() {
    this.getMarkers().then(() => {
      this.initMap();
    });
  },
  methods: {
    async initMap() {
      window._AMapSecurityConfig = {
        securityJsCode: "a997ecf2ab8493db7063d2c7b48c78fc",
      };
      AMapLoader.load({
        key: "386d96346264fe4e681c98d0a993fdea",
        version: "2.0",
        plugins: ["AMap.Scale"],
      })
        .then((AMap) => {
          //创建地图
          this.map = new AMap.Map("container", {
            zoom: 11,
            center: [120.30, 30.33],
            resizeEnable: true,
          });

          this.map.setMapStyle("amap://styles/06c9db82095d1e99e5e827225baf0d70");//设置样式

          //设置图标
          this.icon = new AMap.Icon({
            size: new AMap.Size(20, 28),
            image: MarkerIcon,
            imageOffset: new AMap.Pixel(0, 0),
            imageSize: new AMap.Size(20, 28)
          });

          //添加标点
          this.markers.forEach((item) => {
            const marker = new AMap.Marker({
              position: item.position,
              title: item.name,
              offset: new AMap.Pixel(-11, -30),
              icon: this.icon,
            });
            marker.locationID = item.ID;
            marker.description = item.description;
            marker.name = item.name;
            //添加标点点击事件
            marker.on('click', (event) => {
              const clickedMarker = event.target;
              //自定义信息窗口
              const infoWindow = new AMap.InfoWindow({
                content: `
                  <p style="max-width: 150px; word-wrap: break-word;">
                    <strong style="font-size: 14px;">${clickedMarker.name}</strong><br>
                    <span style="font-size: 12px;display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical; overflow: hidden; text-overflow: ellipsis;">
                      介绍：${clickedMarker.description}
                    </span>
                    <a href="/locations/${clickedMarker.locationID}" target="_blank" style="font-size: 12px;">查看详情</a>
                  </p>
                `,
                offset: new AMap.Pixel(0, -30),
                //size: new AMap.Size(300, 0) 
              });
              infoWindow.open(this.map, clickedMarker.getPosition());
            });

            this.map.add(marker);//添加标点

            this.allmarkers.push(marker);
          });

          //添加地图点击事件
          this.map.on('click', (e) => {

            if (!this.ifaddmarker) {
              return;
            }

            if (e.lnglat && !isNaN(e.lnglat.lng) && !isNaN(e.lnglat.lat)) {

              //添加新标点
              const marker = new AMap.Marker({
                position: e.lnglat,
                icon: this.icon,
                offset: new AMap.Pixel(-11, -30),
              });
              this.map.add(marker);
              this.newmarker = marker;

              //创建地图窗口
              Swal.fire({
                title: '请输入标记标题',
                html: '<input id="swal-input1" class="swal2-input" placeholder="标题" type="text"> ' +
                  '<input id="swal-input2" class="swal2-input" placeholder="描述" type="text"> ',
                showCancelButton: true,
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                focusConfirm: false,
                preConfirm: () => {
                  const title = document.getElementById('swal-input1').value;
                  const description = document.getElementById('swal-input2').value;

                  if (!title) {
                    Swal.showValidationMessage('请输入有效的标题');
                    return false;
                  }
                  return { title, description };
                }
              }).then((result) => {
                if (result.isConfirmed) {
                  const { title, description } = result.value;
                  this.newmarker.description = description;
                  this.newmarker.name = title;
                  this.newmarker.setTitle(title);
                  this.newmarker.locationID = this.addMarkers(title, this.newmarker.getPosition(), description);
                  this.newmarker.on('click', (event) => {
                    const clickedMarker = event.target;
                    const infoWindow = new AMap.InfoWindow({
                      content: `
                        <p style="max-width: 116px; word-wrap: break-word;">
                          <strong style="font-size: 14px;">${clickedMarker.name}</strong><br>
                          <span style="font-size: 12px;display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical; overflow: hidden; text-overflow: ellipsis;">
                            介绍：${clickedMarker.description}
                          </span>
                          <a href="/locations/${clickedMarker.locationID}" target="_blank" style="font-size: 12px;">查看详情</a>
                        </p>
                      `,
                      offset: new AMap.Pixel(79, -30),
                      size: new AMap.Size(300, 0)
                    });
                    infoWindow.open(this.map, clickedMarker.getPosition());
                  });

                  //前往上传界面窗口
                  Swal.fire({
                    title: '创建完成，是否上传资料？',
                    icon: 'question',
                    showCancelButton: true,
                    confirmButtonText: '确认',
                    cancelButtonText: '取消',
                  }).then((result) => {
                    if (result.isConfirmed) {
                      this.$router.push('/User');
                    }
                  });
                }
                else {
                  this.newmarker.setMap(null);
                }

              });
            }
          });

        })
        .catch((e) => {
          console.log(e);
        });
    },

    //从后端获取地点数据
    async getMarkers() {
      try {
        console.log("aa")
        const res = await axios.get('http://127.0.0.1:4523/m1/5546336-5223294-default/locations/filter?page&pageSize');
        const locationIds = res.data.map(item => item.locationID);
        const descriptions = await Promise.all(locationIds.map(id => this.getLocationIntro(id)));
        this.markers = res.data.map((item, index) => ({
          name: item.name,
          position: [item.location.attitude, item.location.latitude],
          ID: item.locationID,
          description: descriptions[index]
        }));
        console.log(this.markers)
      } catch (error) {
        console.error('Failed to fetch markers:', error);
      }
    },

    //从后端获取地点介绍
    async getLocationIntro(locationId) {
      try {
        //console.log('http://127.0.0.1:4523/m1/5546336-5223294-default/locations/'+locationId)
        const res = await axios.get('http://127.0.0.1:4523/m1/5546336-5223294-default/locations/' + locationId);
        //console.log(locationId)
        console.log(res.data.locationInfo[0].locationIntro);
        return res.data.locationInfo[0].locationIntro;
      } catch (error) {
        console.log(locationId)
        console.error('Failed to fetch markers:', error);
        return "无";
      }
    },

    //将新增地点数据传给后端
    async addMarkers(title, position, description) {
      try {
        const res = await axios.post('http://127.0.0.1:4523/m1/5546336-5223294-default/locations', {
          name: title,
          introduction: description,
          location: {},
          attitude: position[1],
          latitude: position[0]
        });
        console.log(res.data);
        this.getMarkers()
        const newMarker = this.markers.find(marker => {
          return marker.name === title &&
            marker.position[0] === position[0] &&
            marker.position[1] === position[1] &&
            marker.introduction === description;
        });
        return newMarker.ID;
      } catch (error) {
        console.error('Failed to add marker:', error);
      }
    },

    //搜索地点
    onSearchInput() {
      if (this.searchKeyword.trim() === '') {
        this.filteredMarkers = [];
      } else {
        this.filteredMarkers = this.markers.filter(marker =>
          marker.name.toLowerCase().includes(this.searchKeyword.toLowerCase())
        );
      }
    },
    handleInputClick(event) {
      event.stopPropagation();
    },
    //前往搜索的地点
    onMarkerClick(marker) {
      if (marker) {
        this.map.setCenter(marker.position);
        this.searchKeyword = marker.name;
        this.onSearchInput();
      }
    },
    onbuttonClick() {
      if (this.ifaddmarker) {
        this.buttonText = '添加标点';
        this.ifaddmarker = false;
      } else {
        this.buttonText = '取消添加标点';
        this.ifaddmarker = true;
      }
    },
  },
};
</script>


<template>
  <div>
    <button class="button" @click="onbuttonClick">
      {{ buttonText }}
    </button>

    <input v-model="searchKeyword" @input="onSearchInput" class="input-search" placeholder="输入关键字搜索"
      @click="handleInputClick" />

    <ul class="search-results" @click="handleInputClick">
      <li v-for="(marker, index) in filteredMarkers" :key="index" @click="() => onMarkerClick(marker)">
        {{ marker.name }}
      </li>
    </ul>
    <div id="container"></div>
  </div>

</template>

<style scoped>
#container {
  position: relative;
  width: 100%;
  height: 900px;
}

.button {
  position: absolute;
  top: 80px;
  left: 10px;
  z-index: 10;
  width: 300px;
  padding: 10px;
  border: 1px solid #ccc;
  background-color: #fcfcfc;
}

.button:hover {
  cursor: pointer;
  background-color: #fe0000;
}

.input-search {
  position: absolute;
  top: 80px;
  right: 10px;
  z-index: 10;
  width: 300px;
  padding: 10px;
  border: 1px solid #ccc;

  /*pointer-events: none;  允许点击事件穿透 */
}

.search-results {
  position: absolute;
  top: 80px;
  right: 10px;
  z-index: 9;
  width: 300px;
  border: 1px solid #000000;
  list-style-type: none;
  padding: 26px 10px 10px;
  margin: 0;
  background-color: #f9f9f9;
}

.search-results li {
  margin: 10px 0;
  border-bottom: 1px solid #ccc;
  padding-bottom: 5px;
}

.search-results li:first-child {

  margin-top: 20px;
}

.search-results li:last-child {
  border-bottom: none;
  /* margin: 0px 0;*/
}

.search-results li:hover {
  background-color: #fe0000;
}

.marker_name {
  font-size: 16px;
}

.description {
  font-size: 12px;
  /* 假设你希望description的字体大小为12px */
  white-space: pre-wrap;
  /* 允许自动换行 */
  overflow: hidden;
  /* 隐藏溢出内容 */
  text-overflow: ellipsis;
  /* 使用省略号表示溢出内容 */
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}
</style>